import { DownOutlined } from '@ant-design/icons';
import { Button, Dropdown, Input, Layout, Menu, message } from 'antd';
import { useState, useEffect, useRef } from 'react';
import axios, { CancelTokenSource } from 'axios';
import DachuangMarket from './DachuangMarket';
import '@/componets/yingyong/ApplicationFunc.scss';
import '@/componets/yingyong/CustomerLoading.scss';

const { Search } = Input;
const { Content, Footer } = Layout;

interface Project {
  projectId: number;
  name: string;
  tags: string[];
  description: string;
  likeNum: number;
  shareNum: number;
  lookNum: number;
  likeTrue: boolean;
  createdTime: string;
  image: string | null;
  introduction: string | null;
  advertise: string | null;
  innovation: string | null;
  projectImages: string[] | null;
}

const sortOptions = [
  { key: 'createdTime', label: '创建时间'},
  { key: 'likenum', label: '喜爱数'},
  { key: 'sharenum', label: '分享数'},
  { key: 'looknum', label: '浏览数'},
];

const filterOptions = [
  { key: 'all', label: '全部' },
  { key: 'favorites', label: '喜欢' }
];

const CustomLoader: React.FC = () => {
  return (
    <div className="custom-loader">
      <div className="loader-circle">
        <div className="loader-inner"></div>
      </div>
      <div className="loader-text">加载中...</div>
    </div>
  );
};

const Dachuangxiangmu: React.FC = () => {
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [sort, setSort] = useState<string>('createdTime');
  const [filter, setFilter] = useState<string>('all');
  const [search, setSearch] = useState<string>('');
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [page, setPage] = useState<number>(1);
  const [hasMore, setHasMore] = useState<boolean>(true);

  const cancelTokenSource = useRef<CancelTokenSource>();

  const fetchProjects = async (reset: boolean = false) => {
    // 取消上一个请求
    if (cancelTokenSource.current) {
      cancelTokenSource.current.cancel('Operation canceled due to new request.');
    }

    // 为新的请求创建一个取消令牌
    cancelTokenSource.current = axios.CancelToken.source();

    console.log(`Fetching projects, page: ${reset ? 1 : page}, reset: ${reset}`);
    console.log(`Request params - pageNum: ${reset ? 1 : page}, sentence: ${search || 'undefined'}, tags: ${selectedCategory === 'all' ? 'undefined' : selectedCategory}, sortBy: ${sort}`);
    setLoading(true);

    try {
      // 创建请求参数对象
      let params: any = {
        pageNum: reset ? 1 : page,
        sortBy: sort,
        userId: 1,
      };

      if (search) {
        params.sentence = search;
      }
      else{
        params.sentence = undefined;
      }

      if (selectedCategory !== 'all') {
        params.tags = selectedCategory;
      }
      else{
        params.tags = undefined;
      }

      const response = await axios.get('http://localhost:8080/api/innovationPlaza/project/getALLProjects', {
        cancelToken: cancelTokenSource.current.token,
        params: params,
      });

      console.log("Response:", response);
      if (response.data.records && response.data.records.length > 0) {
        const newProjects = response.data.records; // 获取 records 中的项目数据
        console.log("Fetched projects:", newProjects);
        setProjects(reset ? newProjects : [...projects, ...newProjects]);
        if (newProjects.length === 0) {
          setHasMore(false); // 如果返回的数据数量为零，不再继续加载
        }
      } else {
        setHasMore(false); // 当 records 为空时不再加载更多
        message.error('Failed to fetch projects');
      }
    } catch (error) {
      if (axios.isCancel(error)) {
        console.log('Request canceled:', error.message);
      } else {
        console.error('Error fetching projects:', error);
        message.error('Error fetching projects');
      }
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchProjects(true);
    // 在组件卸载时取消未完成的请求
    return () => {
      if (cancelTokenSource.current) {
        cancelTokenSource.current.cancel('Component unmounted.');
      }
    };
  }, [selectedCategory, sort, filter, search]);

  useEffect(() => {
    if (page > 1 && hasMore) {
      fetchProjects();
    }
  }, [page]);

  const handleCategoryClick = (category: string) => {
    if (category === '全部'){
        console.log('nothing');
        setSelectedCategory('');
        setPage(1);
        setHasMore(true); // 重置加载更多的状态
        setLoading(true)
    }
    else{
    console.log("Selected category:", category);
    setSelectedCategory(category);
    setPage(1);
    setHasMore(true); // 重置加载更多的状态
    setLoading(true);
    }
  };

  const handleSortChange = ({ key }: any) => {
    console.log("Selected sort:", key);
    setSort(key);
    setPage(1);
    setHasMore(true); // 重置加载更多的状态
    setLoading(true);
  };

  const handleFilterChange = ({ key }: any) => {
    console.log("Selected filter:", key);
    setFilter(key);
    setPage(1);
    setHasMore(true); // 重置加载更多的状态
    setLoading(true);
  };

  const handleSearch = (value: string) => {
    console.log("Search term:", value);
    setSearch(value);
    setPage(1);
    setHasMore(true); // 重置加载更多的状态
    setLoading(true);
  };

  const sortMenu = (
    <Menu onClick={handleSortChange}>
      {sortOptions.map(option => (
        <Menu.Item key={option.key}>
          {option.label}
        </Menu.Item>
      ))}
    </Menu>
  );

  const filterMenu = (
    <Menu onClick={handleFilterChange}>
      {filterOptions.map(option => (
        <Menu.Item key={option.key}>
          {option.label}
        </Menu.Item>
      ))}
    </Menu>
  );

  const categories = [
    { tagId: 'all', tagName: '全部' },
    { tagId: '大语言模型', tagName: '大语言模型' },
    { tagId: 'RAG', tagName: 'RAG' }
  ];

  if (loading && page === 1) {
    return (
      <div className="custom-loader-wrapper">
        <CustomLoader />
      </div>
    );
  }

  return (
    <Layout className="main-layout">
      <Content className="dynamic-content">
        <div className="data-market">
          <div className='top-menu'>
            <h1>应用广场</h1>
            <div className="search-bar">
              <Dropdown overlay={sortMenu}>
                <p style={{ margin: '0 0', cursor: 'pointer' }}>排序：{sortOptions.find(option => option.key === sort)?.label} <DownOutlined /></p>
              </Dropdown>
              <Dropdown overlay={filterMenu}>
                <p style={{ margin: '0 1.25rem', cursor: 'pointer' }}>筛选：{filterOptions.find(option => option.key === filter)?.label} <DownOutlined /></p>
              </Dropdown>
              <Search
                placeholder="搜索项目"
                style={{ width: 240 }}
                onSearch={handleSearch}
              />
              <Button type="primary" className='start-chat-button'>创建项目</Button>
            </div>
          </div>
          <div className="category-menu">
            {categories.map((tag) => (
              <Button
                key={tag.tagId}
                type={selectedCategory === tag.tagName ? 'primary' : 'default'}
                style={{ borderColor: 'white', borderRadius: '0rem' }}
                className='yingyong-tagbutton'
                onClick={() => handleCategoryClick(tag.tagName)}>
                {tag.tagName}
              </Button>
            ))}
          </div>
        </div>
      </Content>
      <Footer className="scrollable-footer">
        <div className="data-list">
          <DachuangMarket projects={projects} loadMoreProjects={() => setPage(page + 1)} />
        </div>
      </Footer>
    </Layout>
  );
};

export default Dachuangxiangmu;
